//
//  FavoriteGoodsView.m
//  phmall
//
//  Created by admin on 2017/10/24.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "FavoriteGoodsView.h"
#import "FavoriteGoodsCell.h"
#import "CategoryModel.h"
#import "GoodsModel.h"
@interface FavoriteGoodsView ()<UICollectionViewDataSource,UICollectionViewDelegate,FavoriteGoodsCellDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    NSInteger       start;
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,assign)EmptyDataSetType emptyType;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation FavoriteGoodsView

-(instancetype)init{
    if (self=[super init]) {
        [self loadNewShop:YES];
        [self addSubview:self.collectionView];
        self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footeRefresh)];
        self.collectionView.mj_footer.hidden=YES;
        self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(HeaderRefresh)];
    }
    return self;
}
-(void)HeaderRefresh{
    start=0;
    [self loadNewShop:NO];
}
-(void)footeRefresh{
    start=self.timeArr.count;
    [self loadNewShop:YES];
}
- (void)loadNewShop:(BOOL)reload{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"favorite/get_favorite"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:@"1" forKey:@"t"];
    [parametersDic setValue:@"20" forKey:@"num"];
    [parametersDic setValue:[NSString stringWithFormat:@"%ld",(long)start] forKey:@"s"];
    [parametersDic setValue:@"0" forKey:@"ism"];
    [parametersDic setValue:@"0" forKey:@"m"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        if (start==0) {
            [self.timeArr removeAllObjects];
        }
        self.emptyType=EmptyDataSetNoData;
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if (responseDict[@"data"] !=[NSNull alloc]) {
            NSMutableArray *data=responseDict[@"data"];
            if (data.count==0) {
                [self.collectionView.mj_header endRefreshing];
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                if (reload) {
                    [self.collectionView reloadData];
                }
            }else{
                [self analysisDataWithNewArray:data];
            }
        }
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.collectionView.mj_footer.hidden=YES;
        [self.timeArr removeAllObjects];
        self.emptyType=EmptyDataSetNoNetwork;
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)analysisDataWithNewArray:(NSMutableArray *)array{
    //    NSMutableArray *goods=[[NSMutableArray alloc] init];
    for (NSDictionary *dict in array)
    {
        GoodsModel *model = [GoodsModel yy_modelWithDictionary:dict];
        [self.timeArr addObject:model];
    }
    if (self.timeArr.count>4) {
        self.collectionView.mj_footer.hidden=NO;
    }else{
        self.collectionView.mj_footer.hidden=YES;
    }
    [self.collectionView reloadData];
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}
-(void)removeAction:(UICollectionViewCell *)cell{
    NSIndexPath *index=[self.collectionView indexPathForCell:cell];
    GoodsModel *model=self.timeArr[index.row];
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"favorite/del_favorite"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setValue:@"1" forKey:@"t"];
    [parametersDic setValue:model.f_uid forKey:@"f"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if ([[NSString stringWithFormat:@"%@",responseDict[@"data"]] isEqualToString:@"1"]) {
                [PublicClass ProgressHUDModeText:Localized(@"删除成功") andTime:2 ];
                start=0;
                [self loadNewShop:YES];
            }
        }
       
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }
    }];
}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGSize superSize = self.frame.size;
    
    if (CGSizeEqualToSize(superSize, CGSizeZero)) {
        return;
    }
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self);
    }];
}

-(NSMutableArray *)timeSort:(NSMutableArray *)array2{
    NSMutableArray *array = [NSMutableArray arrayWithArray:array2];
    NSMutableArray *dateMutablearray = [@[] mutableCopy];
    for (int i = 0; i < array.count; i ++) {
        GoodsModel *model=array[i];
        NSString *string = model.register_date;
        NSMutableArray *tempArray = [@[] mutableCopy];
        [tempArray addObject:model];
        for (int j = i+1; j < array.count; j ++) {
            GoodsModel *jmodel=array[j];
            NSString *jstring = jmodel.register_date;
            
            if([string isEqualToString:jstring]){
                
                [tempArray addObject:jmodel];
                
                [array removeObjectAtIndex:j];
                j -= 1;
                
            }
        }
        [dateMutablearray addObject:tempArray];
    }
    return dateMutablearray;
}
#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.timeArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId=@"cell";
    FavoriteGoodsCell *cell = (FavoriteGoodsCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
//    NSMutableArray *goodsArr=self.timeArr[indexPath.section];
    cell.model=self.timeArr[indexPath.row];
    cell.delegate=self;
    ViewBorderRadius(cell, 10, 0, [UIColor clearColor]);
    return cell;
}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(SCREEN_WIDTH, 44);
//}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    return CGSizeMake(SCREEN_WIDTH, 10);
//}
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (iPhone5SE) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 230);
    }else  if (iPhone6_6s) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }else  if (iPhone6Plus_6sPlus) {
        return CGSizeMake(SCREEN_WIDTH/2-15, 272);
    }else{
        return CGSizeMake(SCREEN_WIDTH/2-15, 252);
    }
}
//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return nil;
            break;
        case EmptyDataSetNoData:
            
            return [UIImage imageNamed:@"订单缺失"];
            break;
        case EmptyDataSetNoNetwork:
            
            return [UIImage imageNamed:@"断网"];
            break;
    }
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    
    switch (self.emptyType) {
        case EmptyDataSetNone:
            return NO;
            break;
        case EmptyDataSetNoData:
            return YES;
            break;
        case EmptyDataSetNoNetwork:
            return NO;
            break;
    }
    return YES;
}
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if (self.emptyType==EmptyDataSetNone) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [activityView startAnimating];
        return activityView;
    }else{
        return nil;
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.emptyType==EmptyDataSetNoData) {
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:@"您的购物车是空的哦！\n跟我去采一些吧。"];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:20],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, 10)];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange(10, 9)];
        return currentPriceStr;
    }
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    if (self.emptyType==EmptyDataSetNoNetwork){
        NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
        [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
        return currentPriceStr;
    }else{
        return nil;
    }
    
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadNewShop:YES];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
}

- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.collectionView.contentOffset = CGPointZero;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        //设置collectionView滚动方向
        //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        //设置headerView的尺寸大小
        //        layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 40);
        //该方法也可以设置itemSize
        layout.itemSize =CGSizeMake(110, 150);
        
        //2.初始化collectionView
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
        
        //3.注册collectionViewCell
        //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
        [_collectionView registerClass:[FavoriteGoodsCell class] forCellWithReuseIdentifier:@"cell"];
        
        _collectionView.showsVerticalScrollIndicator=NO;
//        //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerSelectType"];
//        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerSelectType"];
        //4.设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.emptyDataSetSource = self;
        _collectionView.emptyDataSetDelegate = self;
    }
    return _collectionView;
}
//-(NSMutableArray *)goodsArr{
//    if (!_goodsArr) {
//        _goodsArr=[[NSMutableArray alloc] init];
//    }
//    return _goodsArr;
//}
-(NSMutableArray *)timeArr{
    if (!_timeArr) {
        _timeArr=[[NSMutableArray alloc] init];
    }
    return _timeArr;
}
-(void)reloadData{
    [self.collectionView reloadData];
}
@end
